//
//  MHRegistViewController.m
//  ManHua
//
//  Created by 江子安 on 15/10/30.
//  Copyright © 2015年 蓝欧科技. All rights reserved.
//

#import "MHRegistViewController.h"
#import <AFNetworking.h>
#import "MHUserInfo.h"

@interface MHRegistViewController ()
@property (weak, nonatomic) IBOutlet UITextField *emailTF;
@property (weak, nonatomic) IBOutlet UITextField *passwordTF;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UITextField *repeatPasswordTF;
@property (nonatomic, assign) BOOL result;
@property (nonatomic, strong) MHUserInfo *userInfo;
@property (nonatomic, strong) UITextField *currentTF;

@end

@implementation MHRegistViewController

- (void)dealloc
{
    NSLog(@"MHRegistViewController +++++++ dealloc");
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"注册";
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(registAction:)];
    [self registerForKeyboardNotifications];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hiddenKeyboard)];
    [self.view addGestureRecognizer:tap];
}
- (void) registerForKeyboardNotifications
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}

- (void) keyboardWasShown:(NSNotification *) notif
{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    
    NSLog(@"keyBoard:%f", keyboardSize.height);
    CGFloat viewHeight = CGRectGetMaxY(self.currentTF.frame) + 10;
    NSLog(@"%f", Height - keyboardSize.height - 64);
    if (viewHeight > Height - keyboardSize.height) {
        CGFloat change = keyboardSize.height - (Height - viewHeight);
        NSLog(@"%f", change);
        self.view.center = CGPointMake(self.view.center.x, Height * 0.5 - change);
    }
    
}
- (void) keyboardWasHidden:(NSNotification *) notif
{
    NSDictionary *info = [notif userInfo];
    
    NSValue *value = [info objectForKey:UIKeyboardFrameBeginUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    NSLog(@"keyboardWasHidden keyBoard:%f", keyboardSize.height);
    // keyboardWasShown = NO;
    self.view.center = CGPointMake(Width * 0.5, Height * 0.5);
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if ([textField isEqual:self.emailTF]) {
        [self.passwordTF becomeFirstResponder];
    }
    else if ([textField isEqual:self.passwordTF])
    {
        [self.repeatPasswordTF becomeFirstResponder];
    }
    else if ([textField isEqual:self.repeatPasswordTF])
    {
        [self.nameTF becomeFirstResponder];
    }
    else if ([textField isEqual:self.nameTF])
    {
        [self hiddenKeyboard];
    }
    return YES;
}

- (void)hiddenKeyboard
{
    [self.view endEditing:YES];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    self.currentTF = textField;
}
- (void)requestData
{
    //    http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx?email=jza1314520@qq.com&method=register&nick=%E4%B9%88%E4%B9%88%E5%A4%A7&question=&pwd=19920419&answer=
    NSString *nick = [_nameTF.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dict = [NSDictionary dictionaryWithObjects:@[_emailTF.text,@"register",nick,@"",_passwordTF.text,@""] forKeys:@[@"email",@"method",@"nick",@"question",@"pwd",@"answer"]];
    [[AFHTTPRequestOperationManager manager] GET:@"http://112.124.96.190:9090/bukamanhua5appjobs/ComicHandle.ashx" parameters:dict success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        _result = [responseObject[@"UserResult"]integerValue];
        if (_result == 1) {
            NSDictionary *dictInfo = responseObject[@"UserModel"];
            [self.userInfo setValuesForKeysWithDictionary:dictInfo];
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"注册成功" preferredStyle:(UIAlertControllerStyleAlert)];
            __weak MHRegistViewController *test = self;
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                if (test.autoLoginBlock != nil) {
                    test.autoLoginBlock(_emailTF.text, _passwordTF.text);
                }
            }];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        NSLog(@"%@", error.localizedDescription);
    }];
}

- (void)registAction:(id)sender {
    if (_emailTF.text.length != 0 && _passwordTF.text.length != 0 && _repeatPasswordTF.text.length != 0 && _nameTF.text.length != 0) {
        
        if ([self isValidateEmail:_emailTF.text]) {
            
            if ([_passwordTF.text isEqualToString:_repeatPasswordTF.text]) {
                [self requestData];
            }
            else
            {
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"两次密码不同" preferredStyle:(UIAlertControllerStyleAlert)];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                [alert addAction:action];
                [self presentViewController:alert animated:YES completion:nil];
            }
            
        }
        else
        {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"邮箱格式不正确" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }
    else
    {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请填入完整信息" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
        
    }
    
}

-(BOOL)isValidateEmail:(NSString *)email {
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}

@end
